package com.wk.springbootlearn.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wk.springbootlearn.common.utils.CompareList;
import com.wk.springbootlearn.mapper.*;
import com.wk.springbootlearn.pojo.constant.CodeConstant;
import com.wk.springbootlearn.pojo.constant.Level;
import com.wk.springbootlearn.pojo.constant.Sequence;
import com.wk.springbootlearn.pojo.entity.*;
import com.wk.springbootlearn.pojo.form.UpdateUserForm;
import com.wk.springbootlearn.pojo.form.UserForm;
import com.wk.springbootlearn.common.utils.JwtUtils;
import com.wk.springbootlearn.common.utils.OkHttpCli;
import com.wk.springbootlearn.common.utils.RedisUtils;
import com.wk.springbootlearn.pojo.form.GetUsersForm;
import com.wk.springbootlearn.pojo.form.LoginRequest;
import com.wk.springbootlearn.pojo.model.LoginResponse;
import com.wk.springbootlearn.service.UserService;
import lombok.Setter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GroupUserMapper groupUserMapper;

    @Override
    public IPage findAll(GetUsersForm getUsersForm) {
        // 校验序列
        String sequence = getUsersForm.getSequence();
        if (sequence != null) {
            boolean exist = false;
            for (Sequence value : Sequence.values()) {
                if (value.getCode().equals(sequence)) {
                    exist = true;
                    break;
                }
            }
            if (!exist) throw new RuntimeException("无效的序列：" + sequence);
        }

        // 校验等级
        String level = getUsersForm.getLevel();
        if (level != null) {
            boolean exist = false;
            Level myLevel = null;
            for (Level value : Level.values()) {
                if (value.getCode().equals(level)) {
                    exist = true;
                    myLevel = value;
                    break;
                }
            }
            if (!exist) throw new RuntimeException("无效的等级：" + level);
            // 查看序列与等级是否匹配
            if (sequence != null) {
                if (!myLevel.getSequence().equals(sequence)) {
                    throw new RuntimeException("等级与序列不匹配：（等级：" + level + "；序列：" + sequence + ")");
                }
            }
        }
        // 校验团队id是否有效
        Long teamId = getUsersForm.getTeamId();
        if (teamId != null) {
            Team team = teamMapper.selectById(teamId);
            if (team == null) throw new RuntimeException("无效的团队id：" + teamId);
        }
        // 校验小组id是否有效
        Long groupId = getUsersForm.getGroupId();
        if (groupId != null) {
            MyGroup myGroup = groupMapper.selectById(groupId);
            if (myGroup == null) throw new RuntimeException("无效的小组id：" + groupId);
        }

        Page<User> userPage = new Page<>(getUsersForm.getPage(), getUsersForm.getPageSize());
        return userMapper.findUserList(userPage, getUsersForm);
    }

    @Override
    public LoginResponse login(LoginRequest loginRequest) throws UnsupportedEncodingException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("login_account", loginRequest.getLoginAccount());
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) throw new RuntimeException("账号不存在！");
        // 判断密码是否正确
        String digestPwd = DigestUtils.md5DigestAsHex(loginRequest.getLoginPwd().getBytes(StandardCharsets.UTF_8));
        if (!user.getLoginPwd().equals(digestPwd)) throw new RuntimeException("密码错误！");
        // 生成token
        String token = JwtUtils.generateToken(user.getId().toString());
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setId(user.getId());
        loginResponse.setLoginAccount(user.getLoginAccount());
        loginResponse.setUserName(user.getUserName());
        loginResponse.setToken(token);
        return loginResponse;
    }


    @Override
    @Transactional
    public void createUser(UserForm userForm, Long userId) {
        User user = new User();
        BeanUtils.copyProperties(userForm, user);
        // 对密码进行加密
        String digestPwd = DigestUtils.md5DigestAsHex(user.getLoginPwd().getBytes(StandardCharsets.UTF_8));
        user.setLoginPwd(digestPwd);
        user.setCreator(userId);
        user.setUpdator(userId);
        // 校验序列
        String sequence = user.getSequence();
        if (sequence != null) {
            boolean exist = false;
            for (Sequence value : Sequence.values()) {
                if (value.getCode().equals(sequence)) {
                    exist = true;
                    break;
                }
            }
            if (!exist) throw new RuntimeException("无效的序列：" + sequence);
        }

        // 校验等级
        String level = user.getLevel();
        if (level != null) {
            boolean exist = false;
            Level myLevel = null;
            for (Level value : Level.values()) {
                if (value.getCode().equals(level)) {
                    exist = true;
                    myLevel = value;
                    break;
                }
            }
            if (!exist) throw new RuntimeException("无效的等级：" + level);
            // 查看序列与等级是否匹配
            if (sequence != null) {
                if (!myLevel.getSequence().equals(sequence)) {
                    throw new RuntimeException("等级与序列不匹配：（等级：" + level + "；序列：" + sequence + ")");
                }
            }
        }

        int insert = userMapper.insert(user);

        if (insert > 0) {
            // 建立小组用户关系
            // 查询所属小组是否有效
            Long[] groupIdList = userForm.getGroupIdList();
            if (groupIdList != null && groupIdList.length > 0) {
                for (Long groupId : groupIdList) {
                    MyGroup myGroup = groupMapper.selectById(groupId);
                    if (myGroup == null) throw new RuntimeException("无效的小组id:" + groupId);
                    GroupUser groupUser = new GroupUser();
                    groupUser.setGroupId(groupId);
                    groupUser.setUserId(user.getId());
                    groupUser.setCreator(userId);
                    groupUser.setUpdator(userId);
                    groupUserMapper.insert(groupUser);
                }
            }
        }

    }

    @Override
    @Transactional
    public void updateUser(Long id, UpdateUserForm updateUserForm, Long userId) {
        // 判断用户id是否有效
        User user = userMapper.selectById(id);
        if (user == null) throw new RuntimeException("无效的用户id");
        // 校验序列
        String sequence = updateUserForm.getSequence();
        if (sequence != null) {
            boolean exist = false;
            for (Sequence value : Sequence.values()) {
                if (value.getCode().equals(sequence)) {
                    exist = true;
                    break;
                }
            }
            if (!exist) throw new RuntimeException("无效的序列：" + sequence);
        }

        // 校验等级
        String level = updateUserForm.getLevel();
        if (level != null) {
            boolean exist = false;
            Level myLevel = null;
            for (Level value : Level.values()) {
                if (value.getCode().equals(level)) {
                    exist = true;
                    myLevel = value;
                    break;
                }
            }
            if (!exist) throw new RuntimeException("无效的等级：" + level);
            // 查看序列与等级是否匹配
            if (sequence != null) {
                if (!myLevel.getSequence().equals(sequence)) {
                    throw new RuntimeException("等级与序列不匹配：（等级：" + level + "；序列：" + sequence + ")");
                }
            }
        }
        // 校验小组id是否有效
        Long[] groupIdList = updateUserForm.getGroupIdList();
        QueryWrapper<GroupUser> userQueryWrapper = new QueryWrapper<GroupUser>().eq("user_id", id);
        if (groupIdList == null || groupIdList.length == 0) {
            // 删除用户小组关联记录
            groupUserMapper.delete(userQueryWrapper);
        } else {
            // 判断小组id是否有效
            for (Long groupId : groupIdList) {
                MyGroup myGroup = groupMapper.selectById(groupId);
                if (myGroup == null) throw new RuntimeException("无效的小组id：" + groupId);
            }
            // 获取需要新增或删除的用户小组关联记录
            List<GroupUser> groupUsers = groupUserMapper.selectList(userQueryWrapper);
            List<Long> sourceGroupList = groupUsers.stream().map(GroupUser::getGroupId).collect(Collectors.toList());
            // 需要增加的groupId
            List<Long> addaListThanbList = CompareList.getAddaListThanbList(Arrays.asList(updateUserForm.getGroupIdList()), sourceGroupList);
            // 需要删除的groupId
            List<Long> reduceaListThanbList = CompareList.getReduceaListThanbList(Arrays.asList(updateUserForm.getGroupIdList()), sourceGroupList);
            // 新增用户小组联系
            addaListThanbList.forEach(ele -> {
                GroupUser groupUser = new GroupUser();
                groupUser.setUserId(id);
                groupUser.setGroupId(ele);
                groupUser.setCreator(userId);
                groupUser.setUpdator(userId);
                groupUserMapper.insert(groupUser);
            });
            // 删除用户小组联系
            reduceaListThanbList.forEach(ele -> {
                QueryWrapper<GroupUser> deleteQueryWrapper = new QueryWrapper<GroupUser>().eq("group_id", ele);
                groupUserMapper.delete(deleteQueryWrapper);
            });
        }
        // 更新用户信息
        User user1 = new User();
        user1.setAvatar(updateUserForm.getAvatar());
        user1.setUserName(updateUserForm.getUserName());
        user1.setSequence(updateUserForm.getSequence());
        user1.setLevel(updateUserForm.getLevel());
        user1.setUpdator(userId);
        user1.setId(id);
        userMapper.updateById(user1);
    }

    @Override
    public void updatePwd(Long id, String pwd, Long userId) {
        // 判断用户id是否有效
        User user = userMapper.selectById(id);
        if (user == null) throw new RuntimeException("无效的用户id");
        String digestPwd = DigestUtils.md5DigestAsHex(pwd.getBytes(StandardCharsets.UTF_8));
        User user1 = new User();
        user1.setLoginPwd(digestPwd);
        user1.setUpdator(userId);
        user1.setId(id);
        userMapper.updateById(user1);
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        // 判断用户id是否有效
        User user = userMapper.selectById(id);
        if (user == null) throw new RuntimeException("无效的用户id");
        // 删除该用户与小组的关系记录
        QueryWrapper<GroupUser> queryWrapper = new QueryWrapper<GroupUser>().eq("user_id", id);
        groupUserMapper.delete(queryWrapper);
        // 删除用户
        userMapper.deleteById(id);
    }
}
